<template>
  <div class="my-order">
    <!-- 页面标题和操作按钮 -->
    <div class="header">
      <h2>待审批申请</h2>
      <div class="actions">
        <el-button type="primary" @click="refreshData">刷新数据</el-button>
        <el-button @click="clearFilter">清空筛选</el-button>
      </div>
    </div>

    <!-- 申请列表表格 -->
    <el-table 
      ref="tableRef" 
      :data="tableData" 
      row-key="id" 
      style="width: 100%"
      v-loading="loading"
      element-loading-text="加载中..."
    >
      <el-table-column prop="id" label="申请ID" width="100" />
      <el-table-column prop="name" label="设备名称" width="200" />
      <el-table-column prop="applicanter" label="申请人" width="120" />
      <el-table-column 
        prop="type" 
        label="申请类型" 
        width="100"
        :filters="[
          { text: '使用', value: '使用' },
          { text: '维修', value: '维修' },
        ]"
        :filter-method="filterType"
        filter-placement="bottom-end"
      >
        <template #default="{ row }">
          <el-tag :type="getTypeTagType(row.type)">
            {{ row.type }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remarks" label="申请备注" min-width="200">
        <template #default="{ row }">
          <span v-if="row.remarks && row.remarks.trim()">{{ row.remarks }}</span>
          <span v-else class="no-remarks">无备注</span>
        </template>
      </el-table-column>
      <el-table-column 
        prop="updated_at" 
        label="申请时间" 
        width="180"
        sortable
      >
        <template #default="{ row }">
          {{ formatDateTime(row.updated_at) }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="200">
        <template #default="{ row }">
          <template v-if="row.approval_status === '待审批'">
            <el-button 
              link 
              type="success" 
              size="small" 
              @click="handleApprove(row, true)"
            >
              同意
            </el-button>
            <el-button 
              link 
              type="danger" 
              size="small" 
              @click="handleApprove(row, false)"
            >
              拒绝
            </el-button>
          </template>
          <template v-else>
            <el-tag :type="row.approval_result === '通过' ? 'success' : 'danger'">
              {{ row.approval_result || '已审批' }}
            </el-tag>
          </template>
          <el-button 
            link 
            type="primary" 
            size="small" 
            @click="handleDetail(row)"
          >
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 申请详情对话框 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="申请详情" 
      width="600px"
    >
      <div v-if="selectedApplication" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="申请ID">
            {{ selectedApplication.id }}
          </el-descriptions-item>
          <el-descriptions-item label="设备名称">
            {{ selectedApplication.name }}
          </el-descriptions-item>
          <el-descriptions-item label="申请人">
            {{ selectedApplication.applicanter }}
          </el-descriptions-item>
          <el-descriptions-item label="申请类型">
            <el-tag :type="getTypeTagType(selectedApplication.type)">
              {{ selectedApplication.type }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="申请时间" :span="2">
            {{ formatDateTime(selectedApplication.updated_at) }}
          </el-descriptions-item>
          <el-descriptions-item label="申请备注" :span="2">
            <div class="remarks-content">
              {{ selectedApplication.remarks || '无备注' }}
            </div>
          </el-descriptions-item>
          <el-descriptions-item
            v-if="selectedApplication.approval_status === '已审批'"
            label="审批结果"
            :span="2"
          >
            <el-tag :type="selectedApplication.approval_result === '通过' ? 'success' : 'danger'">
              {{ selectedApplication.approval_result || '无' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <template v-if="selectedApplication && selectedApplication.approval_status === '待审批'">
            <el-button 
              type="success" 
              @click="handleApprove(selectedApplication, true)"
            >
              同意申请
            </el-button>
            <el-button 
              type="danger" 
              @click="handleApprove(selectedApplication, false)"
            >
              拒绝申请
            </el-button>
          </template>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { TableInstance } from 'element-plus'
import axios from 'axios'

// 申请接口类型定义
interface Application {
  id: number
  name: string
  type: string
  remarks: string
  updated_at: string
  applicanter: string
}

// 响应式数据
const tableRef = ref<TableInstance>()
const tableData = ref<Application[]>([])
const loading = ref(false)
const detailDialogVisible = ref(false)
const selectedApplication = ref<Application | null>(null)

// 获取所有待审批请求
const getAllReviewRequests = async () => {
  loading.value = true
  try {
    const response = await axios.get('http://localhost:8080/api/v1/admin/GetAllReview')
    
    if (response.data.code === 200) {
      tableData.value = response.data.data
      console.log('待审批申请数据:', tableData.value)
    } else {
      ElMessage.error(response.data.message || '获取申请列表失败')
    }
  } catch (error) {
    console.error('获取申请列表失败:', error)
    ElMessage.error('网络请求失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 刷新数据
const refreshData = () => {
  getAllReviewRequests()
}

// 清空筛选
const clearFilter = () => {
  tableRef.value!.clearFilter()
}

// 根据申请类型筛选
const filterType = (value: string, row: Application) => {
  return row.type === value
}

// 格式化日期时间
const formatDateTime = (dateStr: string) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 根据申请类型返回对应的标签类型
const getTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    '使用': 'primary',
    '维修': 'warning'
  }
  return typeMap[type] || 'default'
}

// 处理申请详情查看
const handleDetail = (row: Application) => {
  selectedApplication.value = row
  detailDialogVisible.value = true
}

// 处理审批操作
const handleApprove = async (row: Application | null, approve: boolean) => {
  if (!row) return

  const actionText = approve ? '同意' : '拒绝'
  const confirmText = `确定要${actionText}申请人 "${row.applicanter}" 对设备 "${row.name}" 的${row.type}申请吗？`

  try {
    await ElMessageBox.confirm(
      confirmText,
      `${actionText}申请确认`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: approve ? 'success' : 'warning',
      }
    )

    // 调用审批接口
    await reviewApplication(row.id, approve)
    
    // 关闭详情对话框
    if (detailDialogVisible.value) {
      detailDialogVisible.value = false
    }

  } catch (error) {
    if (error !== 'cancel') {
      console.error('审批操作失败:', error)
    }
  }
}

// 审批申请的具体实现
const reviewApplication = async (approveId: number, approve: boolean) => {
  try {
    const approveValue = approve ? 1 : 0
    const response = await axios.post(`http://localhost:8080/api/v1/admin/review/${approveId}/${approveValue}`)
    
    if (response.data.code === 200) {
      const actionText = approve ? '同意' : '拒绝'
      ElMessage.success(`${actionText}申请成功`)
      // 重新加载申请列表
      await getAllReviewRequests()
    } else {
      ElMessage.error(response.data.message || '审批操作失败')
    }
  } catch (error: any) {
    console.error('审批请求失败:', error)
    if (error.response) {
      ElMessage.error(error.response.data.message || '审批操作失败')
    } else {
      ElMessage.error('网络请求失败，请稍后重试')
    }
  }
}

// 组件挂载时获取数据
onMounted(() => {
  getAllReviewRequests()
})
</script>

<style scoped>
.my-order {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.actions {
  display: flex;
  gap: 10px;
}

.no-remarks {
  color: #909399;
  font-style: italic;
}

.detail-content {
  margin: 20px 0;
}

.remarks-content {
  max-height: 120px;
  overflow-y: auto;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  word-break: break-word;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
